package day10;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class Main {
    public static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) throws ParseException {
        System.out.println("请输入年：");
        int year = inputNum(2020,2060);//设定界限
        System.out.println("请输入月");
        int month = inputNum(1,12);
        //创建日历对象
        Calendar cl = Calendar.getInstance();
        //设置日历的年月日
        cl.set(Calendar.YEAR,year);
        cl.set(Calendar.MONTH,month - 1);
        cl.set(Calendar.DATE,1);
        //判断初始值时周几
        int dayOfWeek = cl.get(Calendar.DAY_OF_WEEK);
        //获取本月最大天数
        int dayOfMonth = cl.getActualMaximum(Calendar.DATE);
        //打印日历星期几
        System.out.println("星期日  星期一  星期二  星期三   星期四   星期五   星期六 ");
        //打印第一行空格
        for (int i = 1; i <= dayOfWeek - 1; i++) {
            System.out.print("\t\t");
        }
        int restDays = 0;//休息天数计数器
        int relaxWeekends = 0;//周末休息计数器
        for (int i = 1; i <= dayOfMonth; i++) {
            //天数
            cl.set(Calendar.DATE,i);
            //得到当前日期与初始日期相差的天数
            int day = Days(cl);
            //判断是不是休息日
                if (day % 4 == 0) {
                    System.out.print("[" + i + "]" + "     ");
                    restDays++;
                    //为1是周末，为7是周六

                    if (cl.get(Calendar.DAY_OF_WEEK) == 1 || cl.get(Calendar.DAY_OF_WEEK) == 7) {
                        relaxWeekends++;
                    }
                } else {
                    if(i < 10){
                        System.out.print(i + "       ");
                    }else{
                        System.out.print(i + "      ");
                    }
                }
                if (cl.get(Calendar.DAY_OF_WEEK) == 7) {
                    System.out.println();
                }
        }
        System.out.println("本月休息天数有：" + restDays + "天");
        System.out.println("本月周末休息天数有" + relaxWeekends + "天");


    }

    //上限下限
    public static int inputNum(int min,int max){
        String str = sc.nextLine();
        int num = -1;
        try{
            num = Integer.parseInt(str);
        }catch (NumberFormatException e){
            System.out.println("输入有误，请重新输入");
            return inputNum(min,max);
        }
        if(num<min || num>max){
            System.out.println("输入有误，请重新输入");
            return inputNum(min,max);
        }
        return num;
    }
    //计算相差天数
    public static int Days(Calendar c) throws ParseException {
        Date d = c.getTime();
        long end = d.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
        Date date = format.parse("2020-02-02");
        long start = date.getTime();

        int day = (int)((end - start)/(24*60*60*1000));
        if(end - start < 0){
            return -1;
        }
        return day;
    }
}
